package com.android.fragmentdemo.defineviews
import android.content.Context
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.android.fragmentdemo.R

class GridItemDecoration(context: Context, column: Int) : RecyclerView.ItemDecoration() {

    private val mColumn = column
    private val spaceValue = context.resources.getDimension(R.dimen.dp_10)
    private val space = spaceValue.toInt()
    private val halfSpace = (spaceValue / 2).toInt()

    private var mAddExtraSpace = false

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        super.getItemOffsets(outRect, view, parent, state)
        //val childIndex = parent.getChildAdapterPosition(view)
        val childIndex = (view.layoutParams as RecyclerView.LayoutParams).viewLayoutPosition
        val itemCount = parent.adapter?.itemCount ?: 0
        var bottomSpace = 0
        if (mAddExtraSpace) {
            val remainCount = if (itemCount % mColumn == 0) mColumn else itemCount % mColumn
            val startExtraSpaceCount = itemCount - remainCount
            bottomSpace = if (childIndex >= startExtraSpaceCount) space else 0
        }
        when (childIndex % mColumn) {
            0 -> {
                outRect.set(space, space, halfSpace, bottomSpace)
            }

            mColumn - 1 -> {
                outRect.set(halfSpace, space, space, bottomSpace)
            }

            else -> {
                outRect.set(halfSpace, space, halfSpace, bottomSpace)
            }
        }
    }

    fun setAddExtraSpace(addExtraSpace: Boolean = false) {
        mAddExtraSpace = addExtraSpace
    }
}